package D240607;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class TicketWindows {
    // 线程不安全的
    // static List<String> tickets = new ArrayList();
    // 线程安全的，但是仍有被插入的空间
    // static List<String> tickets = new Vector<>();
    static Queue<String> tickets = new ConcurrentLinkedQueue<>();

    static {
        for (int i = 0; i < 10000; i++) {
            tickets.add("车票编码---" + i);
        }
    }

    public static void main(String[] args) {
        /*for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                // 方法1：加锁
                synchronized (TicketWindows.class) {
                    while (!tickets.isEmpty()) {
                        System.out.println(tickets.remove(0));
                    }
                }
            }).start();
        }*/

        /*for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                // 方法2：更改容器
                synchronized (TicketWindows.class) {
                    while (!tickets.isEmpty()) {
                        // 但是一旦被人插入就会出问题，所以还是需要在外面加一层锁
                        *//*try {
                            Thread.sleep(1);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }*//*
                        System.out.println(tickets.remove(0));
                    }
                }
            }).start();
        }*/

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                // 方法2优化：使用更加优化的容器
                synchronized (TicketWindows.class) {
                    while (true) {
                        String s = tickets.poll();
                        if (s == null){
                            break;
                        } else System.out.println(s);
                    }
                }
            }).start();
        }
    }
}
